package com.Controllers;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.pojo.User;
import com.service.IUserService;

@Controller
public class MyController {

	@Resource
	private IUserService userService;
	@Resource
	private User user;

	@RequestMapping("/add")
	public String add(HttpServletRequest request, Model model) throws UnsupportedEncodingException {

		request.setCharacterEncoding("gbk");
		user.setId(null);
		user.setPassword(request.getParameter("password"));
		user.setUsername(request.getParameter("username"));
		userService.insertSelective(user);
		model.addAttribute("Info", "SUCCESS");

		return "/index";
	}

	@RequestMapping("/delete")
	public String delete(HttpServletRequest request, Model model) {

		userService.deleteById(Integer.valueOf(request.getParameter("id")));
		model.addAttribute("list", userService.selectAll());

		return "/update";
	}

	@RequestMapping("/queryById")
	public String queryById(HttpServletRequest request, Model model) {

		User user = this.userService.getUserById(Integer.valueOf(request.getParameter("id")));
		model.addAttribute("user", user);

		return "/update";
	}

	@RequestMapping("/queryAll")
	public String queryAll(HttpServletRequest request, Model model) {

		List<User> list = this.userService.selectAll();
		model.addAttribute("list", list);

		return "/update";
	}

	@RequestMapping("/update")
	public String update(HttpServletRequest request, Model model) throws UnsupportedEncodingException {

		request.setCharacterEncoding("gbk");
		user.setId(Integer.valueOf(request.getParameter("id")));
		user.setPassword(request.getParameter("password"));
		user.setUsername(request.getParameter("username"));
		this.userService.updateByIdSelective(user);

		model.addAttribute("user", user);

		return "/update";
	}
}
